package com.wardrobe.smartWardrobe.exception;

import com.wardrobe.smartWardrobe.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(WardrobeException.class)
    @ResponseStatus(HttpStatus.OK)
    public R<String> customException(WardrobeException e){
        log.error("[系统异常]{}",e.getErrMessage(),e);
        String errMessage = e.getErrMessage();
        return  R.error(errMessage);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.OK)
    public R<String> methodArgumentNotValidException(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        ArrayList<String> msgList = new ArrayList<>();
        bindingResult.getFieldErrors().stream().forEach(item->msgList.add(item.getDefaultMessage()));
        String msg = StringUtils.join(msgList, ",");
        return R.error(msg);
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public R<String>  elseException(Exception e){
        e.printStackTrace();
        return R.error(CommonError.UNKNOWN_ERROR.getErrMessage());
    }



}
